"use client";

import { useAccount, useConnect, useDisconnect, useSendTransaction, useWaitForTransactionReceipt } from "wagmi";
import { parseEther, parseGwei } from "viem";
import SendETHContract from "@/components/SendETHContract";

function SendETH() {
  const { data: hash, sendTransaction, isError, isIdle, isPending, isSuccess } = useSendTransaction();
  const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({ hash });

  const handleSend = () => {
    sendTransaction({
      to: "0xeffB656E6d161F0230D3078ed268030392002e26", // 接收地址
      value: parseEther("0.01"), // 金额转 Wei
      gasPrice: parseGwei("1"), // 可选 Gas 参数
    });
  };

  return (
    <>
      <button onClick={handleSend} disabled={isPending}>
        {isPending ? "发送中..." : "转账 0.01 ETH"}
      </button>
      <div style={{ marginTop: "10px" }}>
        状态：{isError && <span>error</span>}
        {isIdle && <span>Idle</span>}
        {isSuccess && <span>Success</span>}
      </div>
    </>
  );
}

function App() {
  const account = useAccount();
  const { connectors, connect, status, error } = useConnect();
  const { disconnect } = useDisconnect();

  return (
    <>
      <div>
        <h2>Account</h2>

        <div>
          status: {account.status}
          <br />
          addresses: {JSON.stringify(account.addresses)}
          <br />
          chainId: {account.chainId}
        </div>

        {account.status === "connected" && (
          <button type="button" onClick={() => disconnect()}>
            断开连接Disconnect
          </button>
        )}
      </div>

      <div>
        <h2>连接</h2>
        {connectors.map((connector) => (
          <button key={connector.uid} onClick={() => connect({ connector })} type="button">
            {connector.name}
          </button>
        ))}

        <div style={{ margin: "20px" }}>操作状态：{status}</div>
        {error?.message && <div style={{ color: "red" }}>错误信息：{error?.message}</div>}
      </div>

      <div>
        <h2>转账功能区</h2>
        <div>
          <h4>原生代币转账：useSendTransaction</h4>
          <SendETH />
        </div>
        {/* <div>
          <h4>智能合约转账：useWriteContract</h4>
          <SendETHContract></SendETHContract>
        </div> */}
      </div>
    </>
  );
}

export default App;
